package com.dfd.store.web.servlet;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dfd.store.domain.Category;
import com.dfd.store.service.CategoryService;
import com.dfd.store.service.impl.CategoryServiceImpl;
import com.dfd.store.utils.UUIDUtils;
import com.dfd.store.web.base.BaseServlet;

/**
 * Servlet implementation class AdminServlet
 */
public class AdminCategoryServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	public String findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		CategoryService categoryService = new CategoryServiceImpl();
		List<Category> categorylist = categoryService.getAllCats();
		// 放入request
		req.setAttribute("categorylist", categorylist);
		return "/admin/category/list.jsp";
	}

	public String removeCategory(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String cid = req.getParameter("cid");
		// 调用业务逻辑层
		CategoryService categoryService = new CategoryServiceImpl();
		categoryService.removeCategory(cid);
		resp.sendRedirect(req.getContextPath() + "/AdminCategoryServlet?method=findAll");
		return null;
	}

	public String addCategory(HttpServletRequest req, HttpServletResponse resp) throws Exception {

		return "/admin/category/add.jsp";
	}

	public String editCategory(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String cid = req.getParameter("cid");
		CategoryService categoryService = new CategoryServiceImpl();
		Category categorybyid = categoryService.findById(cid);
		req.setAttribute("categorybyid", categorybyid);
		return "/admin/category/edit.jsp";
	}

	public String save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String cname = req.getParameter("cname");
		// 封装数据
		Category category = new Category();
		category.setCid(UUIDUtils.getId());
		category.setCname(cname);
		// 调用业务逻辑层
		CategoryService categoryService = new CategoryServiceImpl();
		categoryService.save(category);
		// 重定向所有查询
		resp.sendRedirect(req.getContextPath() + "/AdminCategoryServlet?method=findAll");

		return null;
	}

	public String edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String cid = req.getParameter("cid");
		String cname = req.getParameter("cname");
		System.out.println("cid= " + cid + "cname=" + cname);
		Category category = new Category();
		category.setCid(cid);
		category.setCname(cname);
		CategoryService categoryService = new CategoryServiceImpl();
		categoryService.edit(category);
		resp.sendRedirect(req.getContextPath() + "/AdminCategoryServlet?method=findAll");

		return null;
	}

}
